import sys

class ColorConverter:

    colors = {}
    default_color = (0, 0, 0)

    @classmethod
    def load_rgb_txt(cls):
        # TODO: fix the path so that it also works for py2exe executables
        with open('src/rgb.txt') as f:
            for line in f:
                words = line.split()
                rgbt = (int(words[0]), int(words[1]), int(words[2]))
                name = " ".join(words[3:])
                cls.colors[name] = rgbt
                name = "".join(words[3:])
                cls.colors[name] = rgbt
                name = name.lower()
                cls.colors[name] = rgbt

    @classmethod
    def named_color(cls, nm):
        if len(cls.colors) == 0:
            cls.load_rgb_txt()
        return cls.colors.get(nm,  cls.default_color)

    @classmethod
    def rgbt_to_rgbstr(cls, rgbt):
        return "#%02x%02x%02x" % rgbt

    @classmethod
    def rgbstr_to_rgbt(cls, rgbstr):
        offset = 0
        if rgbstr.startswith('#'):
            offset = 1
        return (int(rgbstr[offset:offset+2], 16),
                int(rgbstr[offset+2:offset+4], 16),
                int(rgbstr[offset+4:offset+6], 16))

    @classmethod
    def rgbt_color(cls, colorstr):
        rgbt = cls.named_color(colorstr)
        if rgbt is not None:
            return rgbt

        for c in colorstr:
            if c not in "0123456789aAbBcCdDeEfF#x":
                sys.stderr.write("ERROR: illegal/unknown color: %s (using 0xffffff instead)\n" % 
                                 colorstr)
                colorstr = "ffffff"
                break
        return cls.rgbstr_to_rgbt(colorstr)

if __name__ == "__main__":
    testcolors = ["royalblue4", "RoyalBlue4", "royal blue"]
    for tc in testcolors:
        print "RGB tuple \"%s\" is: %s" % (tc, ColorConverter.rgbt_color(tc))
